package com.ly.mp.busicen.rule.config;

import com.ly.mp.busicen.rule.IRuleReload;
import com.ly.mp.busicen.rule.field.FiledRuleLoader;
import com.ly.mp.busicen.rule.flow.FlowActionLoader;
import com.ly.mp.busicen.rule.instrumentation.plugin.ApiDataInstrumentation;
import com.ly.mp.dal.comm.jdbc.ReadWriteDataSourceDecision;

/**
 * 配置加载拦截-解决中台切换只读库配置加载的问题，一般不用设置
 * @author ly-liuweisong
 *
 */
public class XruleDataLoadCfg {	
	
	public static XruleDataLoadCfg createEmpty() {
		return new XruleDataLoadCfg();
	}
	public static XruleDataLoadCfg createDefault() {
		return createEmpty()
				.fieldLoading((i,m)->m.doo())
				.messageLoading((i,m)->m.doo())
				.flowRuleLoading((i,m)->m.doo())
				.pkPublishLoading((i,m)->{});//默认不开启消息推送
	}
	
	public static XruleDataLoadCfg createBucn() {		
		return createEmpty()
				.fieldLoading(XruleDataLoadCfg::switchTidb)
				.messageLoading(XruleDataLoadCfg::switchTidb)
				.flowRuleLoading(XruleDataLoadCfg::switchTidb)
				.pkPublishLoading(XruleDataLoadCfg::switchTidb);
	}
	
	static <T> void switchTidb(T t,VoidAction va) {
		try {
			ReadWriteDataSourceDecision.markWrite("tidb");
			va.doo();
		} finally {
			ReadWriteDataSourceDecision.reset();
		}
	}
	
	
	/**
	 * 消息
	 */
	private XruleLoading<FiledRuleLoader> messageLoading;
	/**
	 * 字段校验
	 */
	private XruleLoading<FiledRuleLoader> fieldLoading;
	/**
	 * 规则流程
	 */
	private XruleLoading<FlowActionLoader> flowRuleLoading;
	/**
	 * 主键发配
	 */
	private XruleLoading<ApiDataInstrumentation> pkPublishLoading;	
	
	public XruleLoading<ApiDataInstrumentation> pkPublishLoading() {
		return pkPublishLoading!=null?pkPublishLoading:(i,m)->{};
	}

	public XruleDataLoadCfg pkPublishLoading(XruleLoading<ApiDataInstrumentation> pkPublishLoading) {
		this.pkPublishLoading = pkPublishLoading;
		return this;
	}

	public XruleLoading<FiledRuleLoader> messageLoading() {
		return messageLoading!=null?messageLoading:(i,m)->{};
	}

	public XruleLoading<FiledRuleLoader> fieldLoading() {
		return fieldLoading!=null?fieldLoading:(i,m)->{};
	}

	public XruleLoading<FlowActionLoader> flowRuleLoading() {
		return flowRuleLoading!=null?flowRuleLoading:(i,m)->{};
	}
	
	public XruleDataLoadCfg messageLoading(XruleLoading<FiledRuleLoader> messageLoading) {
		this.messageLoading = messageLoading;
		return this;
	}

	public XruleDataLoadCfg fieldLoading(XruleLoading<FiledRuleLoader> fieldLoading) {
		this.fieldLoading = fieldLoading;
		return this;
	}

	public XruleDataLoadCfg flowRuleLoading(XruleLoading<FlowActionLoader> flowRuleLoading) {
		this.flowRuleLoading = flowRuleLoading;
		return this;
	}

	@FunctionalInterface
	public static interface XruleLoading<T extends IRuleReload>{
		 void loading(T t, VoidAction va);	
	}
	
	@FunctionalInterface
	public static interface VoidAction{
		void doo();
	}

}
